<template>
  <div class="app-container">
<!--    电脑端-->
    <div v-if="device !== 'mobile'">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['yjcz:emergencyHandleProcess:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['yjcz:emergencyHandleProcess:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['yjcz:emergencyHandleProcess:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['yjcz:emergencyHandleProcess:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="emergencyHandleProcessList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="pkId" />
        <el-table-column label="节点事项" align="center" prop="nodeContent" />
        <el-table-column label="节点时限要求" align="center" prop="nodeRequireMaxTime" />
        <el-table-column label="节点顺序" align="center" prop="nodeSeq" />
        <el-table-column label="对应的场景关联id" align="center" prop="nodeFbChannelSceneId" />
        <el-table-column label="处置节点联系人id" align="center" prop="nodeContactUserId" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['yjcz:emergencyHandleProcess:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['yjcz:emergencyHandleProcess:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

<!--      <pagination-->
<!--        v-show="total>0"-->
<!--        :total="total"-->
<!--        :page.sync="queryParams.pageNum"-->
<!--        :limit.sync="queryParams.pageSize"-->
<!--        @pagination="getList"-->
<!--      />-->

      <!-- 添加或修改应急处置操作流程对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="节点事项" prop="nodeContent">
            <el-input v-model="form.nodeContent" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="节点时限要求" prop="nodeRequireMaxTime">
            <el-input v-model="form.nodeRequireMaxTime" placeholder="请输入节点时限要求" />
          </el-form-item>
          <el-form-item label="节点顺序" prop="nodeSeq">
            <el-input v-model="form.nodeSeq" placeholder="请输入节点顺序" />
          </el-form-item>
          <el-form-item label="对应的场景关联id" prop="nodeFbChannelSceneId">
            <el-input v-model="form.nodeFbChannelSceneId" placeholder="请输入对应的场景关联id" />
          </el-form-item>
          <el-form-item label="处置节点联系人id" prop="nodeContactUserId">
            <el-input v-model="form.nodeContactUserId" placeholder="请输入处置节点联系人id" />
          </el-form-item>
          <el-form-item label="删除标志" prop="delFlag">
            <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>

<!--    移动端-->
    <div v-if="device === 'mobile'">
      <van-form validate-first @submit="onSubmitFbChannelSceneAndProcess">
        <van-field
          name="场景名称"
          label="场景名称"
          placeholder="请输入场景名称"
          v-model="form.sceneName"
          :rules="[{ required: true, message: '请填写场景名称' }]"
        />
        <van-field
          autosize
          type="textarea"
          name="场景备注"
          label="场景备注"
          placeholder="请输入场景备注"
          v-model="form.sceneRemark"
        />
        <van-divider>应急处置操作流程维护</van-divider>
        <van-collapse v-model="mobilePluginsProp.activeNames">
          <van-swipe-cell v-for="(item, index) in form.templateList" :key="Math.random()" v-if="item.delFlag != '2'">
            <van-collapse-item :title="(item.nodeSeq + 1) + '.' + handleNullColumnValue(item, 'nodeContent', '该节点为示例，请向左滑动修改。')">
              <van-cell-group>
                <van-cell :title="'节点事项：' + handleNullColumnValue(item, 'nodeContent')" />
                <van-cell :title="'节点时限要求：' + handleNullColumnValue(item, 'nodeRequireMaxTime')" />
                <van-cell :title="'处置节点联系人：' + handleNullColumnValue(item.nodeContactUser, 'nickName')" />
                <van-cell :title="'处置节点联系电话：' + handleNullColumnValue(item.nodeContactUser, 'phonenumber')" />
                <van-cell :title="'处置节点备注：' + handleNullColumnValue(item, 'nodeRemark')" />
              </van-cell-group>
            </van-collapse-item>
            <template #right v-if="!search">
              <van-button square style="width: 50px;" type="info" text="" icon="plus" @click="onAddHandleProcess(index)" />
              <van-button square style="width: 50px;" type="primary" text="" icon="edit" @click="onEditHandleProcess(index, item)" />
              <van-button square style="width: 50px;" type="danger" text="" icon="close" @click="onDelHandleProcess(index, item)" v-if="form.templateList.length - alreadyDelCount > 1"/>
              <van-button square style="width: 50px;" type="warning" text="" icon="arrow-up" @click="onUpOrDownHandleProcess(index, true)" v-if="item.nodeSeq > 0" />
              <van-button square style="width: 50px;" type="info" text="" icon="arrow-down" @click="onUpOrDownHandleProcess(index, false)" v-if="item.nodeSeq < form.templateList.length - alreadyDelCount - 1" />
            </template>
          </van-swipe-cell>
        </van-collapse>
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" v-if="!search">
            提交
          </van-button>
          <van-button round block type="info" @click="close" v-if="search">
            返回
          </van-button>
        </div>
      </van-form>



      <van-dialog v-model="mobilePluginsProp.showAddOrModDialog" :title="mobilePluginsProp.dialogTitle" :showCancelButton="true" :showConfirmButton="false" style="height: 90%; overflow-y: auto">
        <van-form validate-first @submit="onSubmitMobileForm">
          <!-- 通过 pattern 进行正则校验 -->
          <van-field
            name="节点事项"
            label="节点事项"
            placeholder="请填写节点事项"
            v-model="handleProcess.nodeContent"
            :rules="[{ required: true, message: '请填写节点事项' }]"
          />

          <van-field
            name="节点时限要求"
            label="节点时限要求"
            placeholder="请填写节点时限要求"
            v-model="handleProcess.nodeRequireMaxTime"
            :rules="[{ required: true, message: '节点时限要求不能为空'}]"
          />

          <van-field-select-picker
            v-model="handleProcess.nodeContactUserId"
            label="处置联系人"
            placeholder="点击选择人员"
            :columns="userList"
            :option="{label:'nickName',value:'userId'}"
            :isSearch="true"
            @confirm="onConfirmContactUser"
          />
          <van-field
            name="联系电话"
            label="联系电话"
            readonly
            placeholder="选择联系人后自动带出"
            v-model="contactUserPhonenumber"
          />
          <van-field
            autosize
            type="textarea"
            name="处置节点备注"
            label="处置节点备注"
            placeholder="请输入处置节点备注"
            v-model="handleProcess.nodeRemark"
          />
          <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit">
              提交
            </van-button>
          </div>
        </van-form>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import {
  listEmergencyHandleProcess,
  getEmergencyHandleProcess,
  delEmergencyHandleProcess,
  addEmergencyHandleProcess,
  updateEmergencyHandleProcess,
  listSceneInfo,
  listUser,
  addOrUpdateHandleProcess,
  listTemplate,
  getHandleProcessByFbChannelSceneId
} from "@/api/yjcz/emergencyHandleProcess";
import {mapState} from "vuex";
import VanFieldSelectPicker from "@/components/VantTools/VanFieldSelectPicker";
import FbAndChannelSelectPicker from "@/components/VantTools/FbAndChannelSelectPicker";
import {Dialog, Notify} from "vant";
import {addOrUpdateSceneAndProcess, checkSceneNameIsExists, getScene} from "@/api/yjcz/scene";

export default {
  name: "PublicHandleProcess",
  computed: {
    ...mapState({
      device: state => state.app.device,
    })
  },
  components: { VanFieldSelectPicker, FbAndChannelSelectPicker },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应急处置操作流程表格数据
      emergencyHandleProcessList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
      },
      // 表单参数
      form: {
        sceneName: '',
        sceneRemark: '',
        templateList: [
          {
            nodeSeq: 0,
          }
        ]
      },
      // 表单校验
      rules: {
      },
      sceneList: [],
      currIdx: 0,
      handleProcess: {},
      userList: [],
      contactUserPhonenumber: '',
      currIsAdd: false,
      mobilePluginsProp: {
        activeNames: [],
        showAddOrModDialog: false,
        dialogTitle: '新增流程节点'
      },
      search: false,
      alreadyDelCount: 0
    };
  },
  created() {
    let pkId = this.$route.query.pkId
    if (pkId) {
      if (Number(this.$route.query.search) === 1) {
        this.search = true
      }
      getScene(pkId).then(response => {
        if (response.code === 200) {
          this.form = response.data
        } else {
          Notify({ type: 'danger', message: response.msg });
        }
      })
    }
    this.getUserList()
  },
  methods: {
    /** 查询应急处置操作流程列表 */
    getList() {
      this.loading = true;
      listEmergencyHandleProcess(this.queryParams).then(response => {
        this.emergencyHandleProcessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scene: {
          sceneName: '',
          sceneRemark: ''
        }
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pkId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加应急处置操作流程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pkId = row.pkId || this.ids
      getEmergencyHandleProcess(pkId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改应急处置操作流程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pkId != null) {
            updateEmergencyHandleProcess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEmergencyHandleProcess(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pkIds = row.pkId || this.ids;
      this.$modal.confirm('是否确认删除应急处置操作流程编号为"' + pkIds + '"的数据项？').then(function() {
        return delEmergencyHandleProcess(pkIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('yjcz/emergencyHandleProcess/export', {
        ...this.queryParams
      }, `emergencyHandleProcess_${new Date().getTime()}.xlsx`)
    },

    handleNullColumnValue (value, propName, valueWhenNull) {
      var propValue
      if (null == value || value == 'undefined' || null == (propValue = value[propName]) || propValue == 'undefined') {
        return valueWhenNull ? valueWhenNull : '暂无'
      }
      return propValue
    },
    onAddHandleProcess (currIdx) {
      this.currIdx = currIdx
      this.handleProcess = {}
      this.contactUserPhonenumber = ''
      this.mobilePluginsProp.showAddOrModDialog = true
      this.mobilePluginsProp.dialogTitle = "新增流程节点"
      this.currIsAdd = true
    },
    onEditHandleProcess (idx, item) {
      this.currIdx = idx
      this.handleProcess = JSON.parse(JSON.stringify(item))
      let nodeContactUser = this.handleProcess.nodeContactUser
      this.contactUserPhonenumber = nodeContactUser ? nodeContactUser.phonenumber : ''
      this.mobilePluginsProp.showAddOrModDialog = true
      this.mobilePluginsProp.dialogTitle = "编辑流程节点"
      this.currIsAdd = false
    },
    onDelHandleProcess (idx, item) {
      let processList = this.form.templateList
      for (let i = idx + 1; i < processList.length; ++ i) {
        processList[i].nodeSeq --
      }
      if (item.hasOwnProperty('pkId') && item.pkId) {
        item.delFlag = '2'
        this.form.templateList = JSON.parse(JSON.stringify(processList))
        this.alreadyDelCount ++
      } else {
        processList.splice(idx, 1)
      }
    },
    onUpOrDownHandleProcess (idx, isUp) {
      let handleProcessList = this.form.templateList
      let currProcess = handleProcessList[idx]
      let needChangeProcess = handleProcessList[isUp ? (idx - 1) : (idx + 1)]
      if (isUp) {
        currProcess.nodeSeq --
        needChangeProcess.nodeSeq ++
      } else {
        currProcess.nodeSeq ++
        needChangeProcess.nodeSeq --
      }
      handleProcessList[isUp ? (idx - 1) : (idx + 1)] = currProcess
      handleProcessList[idx] = needChangeProcess
    },
    getUserList () {
      listUser().then(response => {
        if (response.code === 200) {
          this.userList = response.data
        }
      })
    },
    onConfirmContactUser (value) {
      this.handleProcess.nodeContactUserId = value.userId
      this.contactUserPhonenumber = value.phonenumber
    },
    onSubmitMobileForm () {
      let handleProcessPaste = JSON.parse(JSON.stringify(this.handleProcess))
      let processList = this.form.templateList
      let contactUserId = handleProcessPaste.nodeContactUserId
      if (contactUserId) {
        handleProcessPaste.nodeContactUser = this.userList.find(r => r.userId == contactUserId)
      }
      if (this.currIsAdd) {
        //新增
        let currNodeSeq = processList[this.currIdx].nodeSeq + 1
        handleProcessPaste.nodeSeq = currNodeSeq
        processList.splice(this.currIdx + 1, 0, handleProcessPaste)
        for (let i = this.currIdx + 2; i < processList.length; ++ i) {
          processList[i].nodeSeq ++
        }
      } else {
        // 修改
        Object.assign(processList[this.currIdx], handleProcessPaste)
      }
      this.mobilePluginsProp.showAddOrModDialog = false
    },
    onSubmitFbChannelSceneAndProcess () {
      let processList = this.form.templateList
      for (let i = 0; i < processList.length; ++ i) {
        let process = processList[i]
        if (!process.nodeContent) {
          Notify({ type: 'danger', message: `序号为：${process.nodeSeq + 1}的节点事项不能为空` });
          return
        }
        if (!process.nodeRequireMaxTime) {
          Notify({ type: 'danger', message: `序号为：${process.nodeSeq + 1}的节点时限要求不能为空` });
          return
        }
      }
      checkSceneNameIsExists({sceneName: this.form.sceneName, pkId: this.form.pkId}).then(res => {
        if (res.code === 200) {
          if (res.data) {
            Notify({ type: 'danger', message: `场景名称【${this.form.sceneName}】已存在，请修改` });
            return
          }
          addOrUpdateSceneAndProcess(this.form).then(response => {
            if (response.code === 200) {
              Notify({ type: 'success', message: `${this.form.pkId ? '修改' : '添加'}成功` });
              this.close()
            } else {
              Notify({ type: 'danger', message: response.msg });
            }
          })
        }
      })
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: "/yjcz/fbChannelScene", query: { t: Date.now(), sceneName: this.$route.query.sceneName, type: 'publicScene' } };
      this.$tab.closeOpenPage(obj);
    },
  }
};
</script>
